#include "bytes.h"
#include <cstring>

// 默认构造函数
Bytes::Bytes() : bytes(nullptr), length(0) {}

// 将 uint32_t 转换为字节数组
void Bytes::frome_u32(uint32_t value, DataTyep_t type) {
    delete[] bytes; // 释放之前的内存
    length = 4;
    bytes = new uint8_t[length];
    if (type == LittleEnd) {
        for (int i = 0; i < 4; ++i) {
            bytes[i] = static_cast<uint8_t>(value >> (i * 8));
        }
    } else {
        for (int i = 0; i < 4; ++i) {
            bytes[i] = static_cast<uint8_t>(value >> ((3 - i) * 8));
        }
    }
}

// 将 uint16_t 转换为字节数组
void Bytes::frome_u16(uint16_t value, DataTyep_t type) {
    delete[] bytes; // 释放之前的内存
    length = 2;
    bytes = new uint8_t[length];
    if (type == LittleEnd) {
        bytes[0] = static_cast<uint8_t>(value & 0xFF);
        bytes[1] = static_cast<uint8_t>(value >> 8);
    } else {
        bytes[0] = static_cast<uint8_t>(value >> 8);
        bytes[1] = static_cast<uint8_t>(value & 0xFF);
    }
}

// 将 uint8_t 转换为字节数组
void Bytes::frome_u8(uint8_t value, DataTyep_t type) {
    delete[] bytes; // 释放之前的内存
    length = 1;
    bytes = new uint8_t[length];
    bytes[0] = value;
}

// 将字节数组转换为 uint32_t
uint32_t Bytes::to_u32(uint8_t* inputBytes, DataTyep_t type) {
    uint32_t result = 0;
    if (type == LittleEnd) {
        for (int i = 0; i < 4; ++i) {
            result |= static_cast<uint32_t>(inputBytes[i]) << (i * 8);
        }
    } else {
        for (int i = 0; i < 4; ++i) {
            result |= static_cast<uint32_t>(inputBytes[i]) << ((3 - i) * 8);
        }
    }
    return result;
}

// 将字节数组转换为 uint16_t
uint16_t Bytes::to_u16(uint8_t* inputBytes, DataTyep_t type) {
    uint16_t result = 0;
    if (type == LittleEnd) {
        result = static_cast<uint16_t>(inputBytes[0]) | (static_cast<uint16_t>(inputBytes[1]) << 8);
    } else {
        result = static_cast<uint16_t>(inputBytes[1]) | (static_cast<uint16_t>(inputBytes[0]) << 8);
    }
    return result;
}

// 将字节数组转换为 int32_t
int32_t Bytes::to_i32(uint8_t* inputBytes, DataTyep_t type) {
    return static_cast<int32_t>(to_u32(inputBytes, type));
}

// 将字节数组转换为 int16_t
int16_t Bytes::to_i16(uint8_t* inputBytes, DataTyep_t type) {
    return static_cast<int16_t>(to_u16(inputBytes, type));
}

// 将字节数组转换为 float
float Bytes::to_float(uint8_t* inputBytes, DataTyep_t type) {
    uint32_t intValue = to_u32(inputBytes, type);
    float result;
    std::memcpy(&result, &intValue, sizeof(float));
    return result;
}

// 析构函数
Bytes::~Bytes() {
    delete[] bytes;
    bytes = nullptr;
}